package com.huafeng.commonutil;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * @author 花风
 * @date 2023/8/17 15:18
 * @Description jwt工具类
 */
public class JwtHelper {
    private JwtHelper(){

    }
    private static final long TOKEN_EXPIRE = 3600000;
    private static final String SECRET_KEY = "huafeng";

    /**
     * 根据userId和username生成token
     * @param userId 用户id
     * @param username 用户名
     * @return 生成的token
     */
    public static String createToken(Long userId,String username){
        return Jwts.builder()
                .setSubject("Auth-User")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE))
                .claim("userId",userId)
                .claim("username",username)
                .signWith(SignatureAlgorithm.HS512,SECRET_KEY)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }


    /**
     * 从token中获取用户id
     * @param token token字符串
     * @return 用户id
     */
    public static Long getUserId(String token){
        try {
            if (StringUtils.isEmpty(token) || StringUtils.isBlank(token)){
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims.get("userId",Long.class);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从token中获取用户名
     * @param token token字符串
     * @return 用户名
     */
    public static String getUserName(String token){
        try {
            if (StringUtils.isEmpty(token) || StringUtils.isBlank(token)) {
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims.get("username",String.class);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
